//
//  EmotionView.swift
//  01表情键盘
//
//  Created by SteveLi on 2017/10/24.
//  Copyright © 2017年 李军桦. All rights reserved.
//

import UIKit
//可重用cell Id
let EmotionViewCellId = "EmotionViewCellId"

//MARK:--表情键盘视图
class EmotionView: UIView {
    //选中表情回调
    var selectedEmotionCallBack:(_ emotion: Emoticon) -> ()
    //MARK:---监听方法
    @objc  func clickItem(item:UIBarButtonItem) {
        print("选中分类\(item.tag)")
        let indexPath = IndexPath(item: 0, section: item.tag)
        //滚动collectionView
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
    }

    //MARK： --构造函数
    init(selectedEmoticon: @escaping (_ emoticon: Emoticon)-> ()) {
        //记录闭包属性
        selectedEmotionCallBack = selectedEmoticon
        //调用父类的构造函数
        var rect = UIScreen.main.bounds
        rect.size.height  = 226
        super.init(frame: rect)
        backgroundColor = UIColor.red
        setupUI()
        //滚动到第一页
        let indexPath = IndexPath(item: 0, section: 1)
        DispatchQueue.main.async() { () -> Void in
            self.collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK:- 懒加载控件
    lazy var collectionView:UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout:EmoticonLayout())
    lazy var toolbar = UIToolbar()
    //表情包数组
    lazy var packages = EmoticonManager.sharedManager.packages
    //MARK: --表情布局(类中类---只允许被包含的类使用)
    class EmoticonLayout: UICollectionViewFlowLayout{
        //collectionView 第一次布局的时候被自动调用
        //collectionView 的尺寸已经被设置好 226 toolbar 36 ,如果在 iphone6 + 屏幕宽度是414
        //如果 toolbar 设置为44 ，同样只能显示两行
        override func prepare() {
            super.prepare()
            let col: CGFloat = 7
            let row: CGFloat = 3
            let w = collectionView!.bounds.width / col
            //如果 *0.5 如果在iphone4的屏幕，只能显示两行
            let margin = (collectionView!.bounds.height - row * w) * 0.499
            
            itemSize = CGSize(width: w, height: w)
            minimumLineSpacing = 0
            minimumInteritemSpacing = 0
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            scrollDirection = .horizontal
            collectionView?.isPagingEnabled = true
            //关闭弹簧效果
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
}
//MARK: --- 设置界面
 extension EmotionView {
    //设置界面
    func setupUI() {
        //1.添加控件
        addSubview(toolbar)
        addSubview(collectionView)
        //2.自动布局
        toolbar.snp.makeConstraints { (make) in
            make.bottom.equalTo(self.snp.bottom)
            make.left.equalTo(self.snp.left)
            make.right.equalTo(self.snp.right)
            make.height.equalTo(44)
        }
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(self.snp.top)
            make.bottom.equalTo(toolbar.snp.top)
            make.left.equalTo(self.snp.left)
            make.right.equalTo(self.snp.right)
        }
        //3.准备控件
        prepareToolbar()
        prepareCollectionView()
    }
    

    //准备工具栏
    func prepareToolbar()  {
        //0.tintColor
        toolbar.tintColor = UIColor.darkGray
        //1.设置按钮内容
        var items = [UIBarButtonItem]()
        //toolbar 中，通常是一组功能相近的操作，只是操作的类型不同，通常利用 tag 来区分
        var index = 0
        for p in packages {
            
            items.append(UIBarButtonItem(title:p.group_name_cn , style: .plain, target: self, action:#selector(clickItem(item:))))
            index += 1
            items.last?.tag = index - 1
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        //2.设置items
        toolbar.items = items
    }
    //准备collectionView
    func prepareCollectionView(){
        collectionView.backgroundColor = UIColor.lightGray
        //注册cell
        collectionView .register(EmotionViewCell.self, forCellWithReuseIdentifier: EmotionViewCellId)
        //设置数据源
        collectionView.dataSource = self
        //设置代理
        collectionView.delegate = self
    }
}

//MARK: - UICollectionViewDataSource
extension EmotionView: UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //获取表情包模型
        let em = packages[indexPath.section].emoticons[indexPath.item]
        //执行‘回调’
        selectedEmotionCallBack(em)
    }
    
    //返回分组数量--表情包的数量
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return packages.count
    }
    //返回美国表情包中的表情数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmotionViewCellId, for: indexPath) as! EmotionViewCell
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        return cell
    }
}
//MARK: -表情视图 Cell
class EmotionViewCell: UICollectionViewCell {
    ///表情模型
    
    var emoticon:Emoticon?{
        didSet{
            emotionButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), for: UIControlState.normal)
            emotionButton.setTitle(emoticon?.emoji, for: UIControlState.normal)
            //设置删除按钮
            if emoticon!.isRemoved {
                emotionButton.setImage(UIImage(named: "compose_emotion_delete"), for: UIControlState.normal)
            }
            //设置 emoji,千万不要加上判断，否则显示会不正常
            if emoticon?.emoji != nil {
            }
        }
    }
    
    
    //MARK:--构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(emotionButton)
        emotionButton.backgroundColor = UIColor.white
        emotionButton.setTitleColor(UIColor.black, for: .normal)
        emotionButton.frame = bounds.insetBy(dx: 4, dy: 4)
        //字体的大小和高度相近
        emotionButton.titleLabel?.font = UIFont.systemFont(ofSize: 32)
        emotionButton.isUserInteractionEnabled = false
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK:---懒加载控件
    lazy var emotionButton: UIButton = UIButton()
    
}



